package reply

import (
	"bytes"
	"go_redis_service/interface/IResp"
	"strconv"
)

var (
	NULLBulkReplyBytes = []byte("$-1")
	CRLF               = "\r\n"
)

// BulkReply
// @Description: 返回字符串
type BulkReply struct {
	Arg []byte // moody $5\r\nmoody\r\n
}

func (b *BulkReply) ToBytes() []byte {
	if len(b.Arg) == 0 {
		return NULLBulkReplyBytes
	}
	// moody $5\r\nmoody\r\n
	return []byte("$" + strconv.Itoa(len(b.Arg)) + CRLF + string(b.Arg) + CRLF)
}

func NewBulkReply(arg []byte) *BulkReply {
	return &BulkReply{Arg: arg}
}

// MultiBulkReply
// @Description: 返回数组
type MultiBulkReply struct {
	Args [][]byte
}

func (m *MultiBulkReply) ToBytes() []byte {
	argLen := len(m.Args)
	buffer := &bytes.Buffer{}
	buffer.WriteString("*" + strconv.Itoa(argLen) + CRLF)
	for _, arg := range m.Args {
		if arg == nil {
			buffer.WriteString(string(NULLBulkReplyBytes) + CRLF)
		} else {
			buffer.WriteString("$" + strconv.Itoa(len(arg)) + CRLF + string(arg) + CRLF)
		}
	}
	return buffer.Bytes()
}

func NewMultiBulkReply(args [][]byte) *MultiBulkReply {
	return &MultiBulkReply{Args: args}
}

// StatusReply
// @Description: 状态回复
type StatusReply struct {
	Status string
}

func (s *StatusReply) ToBytes() []byte {
	return []byte("*" + s.Status + CRLF)
}
func NewStatusReply(status string) *StatusReply {
	return &StatusReply{Status: status}
}

func IsErrRepy(reply IResp.Reply) bool {
	return reply.ToBytes()[0] == '-'
}

type IntReply struct {
	Code int64
}

func (i *IntReply) ToBytes() []byte {
	return []byte(":" + strconv.FormatInt(i.Code, 10) + CRLF)
}
func NewIntReply(code int64) *IntReply {
	return &IntReply{Code: code}
}
